package com.ultimate.management.config;

import com.sun.org.apache.xerces.internal.util.EntityResolverWrapper;
import com.ultimate.management.entity.SysUser;
import com.ultimate.management.service.SysUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.LockedException;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;

import java.util.HashSet;
import java.util.Set;

/**
 * @Author LH
 * @Date 2024/2/28 16:52
 * @PackageName com.ultimate.management.config
 * @Description: 这是一个自定义认证
 */
//@Component
public class UserAuthenticationProvider {
    //implements AuthenticationProvider
    @Autowired
    private SysUserService sysUserService;

    public Authentication authenticate(Authentication authentication) throws AuthenticationException {

        //获取表单输入中返回的用户名
        String userName = (String) authentication.getPrincipal();
        //获取表单中输入的密码
        String password = (String) authentication.getCredentials();

        //查询用户是否存在
        SysUser userInfo = sysUserService.getUserInfo(userName);

        if(userInfo.getUsername() == null || userInfo.getUsername() == ""){
            throw new UsernameNotFoundException("用户名不存在");
        }

        //判断密码是否正确,这里我们的密码通过BCrytPasswordEncoder进行加密
        if(!new BCryptPasswordEncoder().matches(password,userInfo.getPassword())){
            throw new BadCredentialsException("密码不正确");
        }

        //判断用户是否停用
        if( "1".equals(userInfo.getStatus())){
            throw new LockedException("该用户已被冻结");
        }

        //角色集合
        Set<GrantedAuthority> authorities = new HashSet<>();

//        EntityResolverWrapper


        return null;
    }


    public boolean supports(Class<?> authentication) {
        return false;
    }
}
